package com.cargo.base.utils;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * <b>XML配置参数读取工具类</b>
 * 
 * @author xiongchun
 */
@SuppressWarnings("rawtypes")
public class AXmlHandler {

	private static Logger log = LoggerFactory.getLogger(AXmlHandler.class);

	private static Map<String, Object> parameterCacheDto = null;

	static {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (log.isDebugEnabled()) {
			log.debug("解析XML参数配置文件...");
		}
		parameterCacheDto = new HashMap<>();
		InputStream is = classLoader.getResourceAsStream("redis-config.xml");
		Document document = parse(is);
		Element elRoot = document.getRootElement();
		Iterator elIt = elRoot.elementIterator();
		while (elIt.hasNext()) {
			Element el = (Element) elIt.next();
			Attribute attrKey = el.attribute("key");
			String keyString = attrKey.getText();
			Attribute attrValue = el.attribute("value");
			String valueString = attrValue.getText();
			parameterCacheDto.put(keyString, valueString);
		}
	}

	/**
	 * 将InputStream输入流解析为Document对象
	 *
	 * @param
	 * @return
	 */
	public static Document parse(InputStream inputStreamXml) {
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			document = saxReader.read(inputStreamXml);
		} catch (DocumentException e) {
			throw new RuntimeException("XML资料格式转换出错.", e);
		}
		return document;
	}

	/**
	 * 获取[applicationParam.xml]配置参数
	 * 
	 * @param pKey
	 * @return
	 */
	public static String getValue(String pKey) {
		String value = parameterCacheDto.get(pKey).toString();
		return value;
	}

}
